pangolin/src/app/admin/idp/[idpId]/policies/EditPolicyForm.tsx

368 lines
17 KiB
TypeScript

import {
Credenza,
CredenzaBody,
CredenzaClose,
CredenzaContent,
CredenzaDescription,
CredenzaFooter,
CredenzaHeader,
CredenzaTitle
} from "@app/components/Credenza";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { PolicyRow } from "./PolicyTable";
import { Button } from "@app/components/ui/button";
import { useState } from "react";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage
} from "@app/components/ui/form";
import { Input } from "@app/components/ui/input";
import {
Popover,
PopoverContent,
PopoverTrigger
} from "@app/components/ui/popover";
import { cn } from "@app/lib/cn";
import { CaretSortIcon, CheckIcon } from "@radix-ui/react-icons";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList
} from "@app/components/ui/command";
import type { Org } from "@server/db/schemas";
import { AxiosResponse } from "axios";
import { CreateIdpOrgPolicyResponse } from "@server/routers/idp";
import { toast } from "@app/hooks/useToast";
type EditPolicyFormProps = {
idpId: string;
orgs: Org[];
policies: PolicyRow[];
policyToEdit: PolicyRow | null;
open: boolean;
setOpen: (open: boolean) => void;
afterCreate?: (policy: PolicyRow) => void;
afterEdit?: (policy: PolicyRow) => void;
};
const formSchema = z.object({
orgId: z.string(),
roleMapping: z.string().optional(),
orgMapping: z.string().optional()
});
export default function EditPolicyForm({
idpId,
orgs,
policies,
policyToEdit,
open,
setOpen,
afterCreate,
afterEdit
}: EditPolicyFormProps) {
const [loading, setLoading] = useState(false);
const [orgsPopoverOpen, setOrgsPopoverOpen] = useState(false);
const api = createApiClient(useEnvContext());
const defaultValues = {
roleMapping: "",
orgMapping: ""
};
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues,
// @ts-ignore
values: policyToEdit
? {
orgId: policyToEdit.orgId,
roleMapping: policyToEdit.roleMapping || "",
orgMapping: policyToEdit.orgMapping || ""
}
: defaultValues
});
async function onSubmit(values: z.infer<typeof formSchema>) {
setLoading(true);
if (policyToEdit) {
const res = await api
.post<AxiosResponse<CreateIdpOrgPolicyResponse>>(
`/idp/${idpId}/org/${values.orgId}`,
{
roleMapping: values.roleMapping,
orgMapping: values.orgMapping
}
)
.catch((e) => {
toast({
variant: "destructive",
title: "Failed to create org policy",
description: formatAxiosError(
e,
"An error occurred while updating the org policy."
)
});
});
if (res && res.status === 200) {
toast({
variant: "default",
title: "Org policy created",
description: "The org policy has been successfully updated."
});
setOpen(false);
if (afterEdit) {
afterEdit({
orgId: values.orgId,
roleMapping: values.roleMapping ?? null,
orgMapping: values.orgMapping ?? null
});
}
}
} else {
const res = await api
.put<AxiosResponse<CreateIdpOrgPolicyResponse>>(
`/idp/${idpId}/org/${values.orgId}`,
{
roleMapping: values.roleMapping,
orgMapping: values.orgMapping
}
)
.catch((e) => {
toast({
variant: "destructive",
title: "Failed to create role",
description: formatAxiosError(
e,
"An error occurred while creating the role."
)
});
});
if (res && res.status === 201) {
toast({
variant: "default",
title: "Org policy created",
description: "The org policy has been successfully created."
});
setOpen(false);
if (afterCreate) {
afterCreate({
orgId: values.orgId,
roleMapping: values.roleMapping ?? null,
orgMapping: values.orgMapping ?? null
});
}
}
}
setLoading(false);
}
return (
<Credenza
open={open}
onOpenChange={(val) => {
setOpen(val);
setLoading(false);
setOrgsPopoverOpen(false);
form.reset();
}}
>
<CredenzaContent>
<CredenzaHeader>
<CredenzaTitle>
{policyToEdit ? "Edit" : "Create"} Organization Policy
</CredenzaTitle>
<CredenzaDescription>
Configure access for an organization
</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
id="edit-policy-form"
>
<FormField
control={form.control}
name="orgId"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Organization</FormLabel>
{policyToEdit ? (
<Input {...field} disabled />
) : (
<Popover
open={orgsPopoverOpen}
onOpenChange={
setOrgsPopoverOpen
}
>
<PopoverTrigger asChild>
<FormControl>
<Button
variant="outline"
role="combobox"
className={cn(
"justify-between",
!field.value &&
"text-muted-foreground"
)}
>
{field.value ??
"Select organization"}
<CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="p-0">
<Command>
<CommandInput placeholder="Search site" />
<CommandList>
<CommandEmpty>
No site found.
</CommandEmpty>
<CommandGroup>
{orgs.map(
(org) => {
if (
policies.find(
(
p
) =>
p.orgId ===
org.orgId
)
) {
return undefined;
}
return (
<CommandItem
value={
org.orgId
}
key={
org.orgId
}
onSelect={() => {
form.setValue(
"orgId",
org.orgId
);
setOrgsPopoverOpen(
false
);
}}
>
<CheckIcon
className={cn(
"mr-2 h-4 w-4",
org.orgId ===
field.value
? "opacity-100"
: "opacity-0"
)}
/>
{
org.name
}
</CommandItem>
);
}
)}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)}
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="roleMapping"
render={({ field }) => (
<FormItem>
<FormLabel>
Role Mapping Path (Optional)
</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormDescription>
JMESPath to extract role information
from the ID token. The result of
this expression must return the role
name(s) as defined in the
organization as a string/list of
strings.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="orgMapping"
render={({ field }) => (
<FormItem>
<FormLabel>
Organization Mapping Path (Optional)
</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormDescription>
JMESPath to extract organization
information from the ID token. This
expression must return thr org ID or
true for the user to be allowed to
access the organization.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</CredenzaBody>
<CredenzaFooter>
<CredenzaClose asChild>
<Button variant="outline">Close</Button>
</CredenzaClose>
<Button
type="submit"
form="edit-policy-form"
loading={loading}
disabled={loading}
>
{policyToEdit ? "Edit" : "Create"} Policy
</Button>
</CredenzaFooter>
</CredenzaContent>
</Credenza>
);
}